package cn.edu.scau.cmi.front.service;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.hibernate.engine.query.spi.HQLQueryPlan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import cn.edu.scau.cmi.ema.domain.Address;
import cn.edu.scau.cmi.ema.domain.Adultertype;
import cn.edu.scau.cmi.ema.domain.Event;
import cn.edu.scau.cmi.ema.domain.Food;
import cn.edu.scau.cmi.ema.domain.Foodbatch;
import cn.edu.scau.cmi.ema.domain.Foodtype;
import cn.edu.scau.cmi.ema.domain.Picture;
import cn.edu.scau.cmi.ema.domain.Subject;
import cn.edu.scau.cmi.ema.domain.User;
import cn.edu.scau.cmi.ema.domain.Video;
import cn.edu.scau.cmi.ema.domain.base.CmiPagination;
import cn.edu.scau.cmi.ema.service.base.CmiEmaService;
import cn.edu.scau.cmi.ema.service.base.CmiPaginationService;
import cn.edu.scau.cmi.ema.service.base.CmiPsonService;
import cn.edu.scau.cmi.ema.service.base.FrontEventSqlService;
import cn.edu.scau.cmi.ema.util.CmiEntityUtil;
import cn.edu.scau.cmi.ema.util.CmiSetUtil;
import cn.edu.scau.cmi.ema.util.CmiSqlUtil;
import cn.edu.scau.cmi.front.dao.CmiAddressDAO;
import cn.edu.scau.cmi.front.dao.CmiEventDAO;
import cn.edu.scau.cmi.front.domain.AddressWrap;
import cn.edu.scau.cmi.front.domain.FrontEventPagination;

/**
 * Spring service that handles CRUD requests for FrontService
 * 
 */

@Service("FrontEventService")

@Transactional
public class FrontEventServiceImpl extends CmiEmaService implements FrontEventService {

	@Autowired
	CmiPsonService cmiPsonService;

	@Autowired
	CmiAddressDAO cmiAddressDAO;

	@Autowired
	CmiEventDAO cmiEventDAO;
	
	@Autowired
	FrontEventSqlService frontEventSqlService;
	
//	根主要食物类型和根掺假类型空，当需要的时候再查找数据库并设置
	private static List<Foodtype> mainRootFoodtypes = new ArrayList<Foodtype>();
	private static List<Adultertype> mainRootAdultertypes = new ArrayList<Adultertype>();
	
//	必须在@Autowired后面添加注解Qualifier. @Autowired是根据类型自动注入，
//	而CmiPaginationService有子类，导致封装时不知是这个类还是这个类的子类，导致封装失败 
	@Autowired
	@Qualifier("CmiPaginationService")
	CmiPaginationService cmiPaginationService;

	public FrontEventServiceImpl() {
	}

	//	保存事件到Json文件   这个方法可以改进为saveEntity2JsonFile(Entity entity,String eventUploadDirectory, String fileNameCommon)
	//每次传过来一个entity分别保存更好，需要保存就调用一次，如果后期需要保存更多entity就无须改动这个方法了
	public void saveEntity2JsonFile(Map<String, Object> objects, String eventUploadDirectory, String fileNameCommon)	throws FileNotFoundException, IOException {
		Event event = (Event)objects.get("event");
		Food food = (Food)objects.get("food");
		AddressWrap discoveryAddressWrap = (AddressWrap)objects.get("discoveryAddressWrap");
		
		
		String eventContents = cmiPsonService.toJsonString(event, 2);
		String foodContents = cmiPsonService.toJsonString(food, 2);
		String discoveryAddressWrapContents = cmiPsonService.toJsonString(discoveryAddressWrap, 2);
		
		String eventFileName = eventUploadDirectory+"/event_"+fileNameCommon + ".json";
		String foodFileName = eventUploadDirectory+"/food_"+fileNameCommon+ ".json";
		String addressFileName = eventUploadDirectory+"/discoveryAddress_"+fileNameCommon+ ".json";

		Charset encoding = Charset.forName("utf8");

		FileUtils.write(new File(eventFileName), eventContents, encoding);
		FileUtils.write(new File(foodFileName), foodContents, encoding);
		FileUtils.write(new File(addressFileName), discoveryAddressWrapContents, encoding);
	}
	
	//	TODO 图片没有封装进来。20202-0308
	/**
	 * 该方法用于封装Event与Food
	 * 分两种情况：
	 * 1、上传事件具有父事件 ：上传事件的相关关联实体与父事件一致   Food也与父事件一致
	 * 2、上传事件不具有父事件：Food与页面选择或新建的食物一致   Event与页面提供的信息一致
	 * 3、此处Address为discoveryAddress，后期可以考虑把sourceAddress也包装进来
	 * @param multipartFiles
	 * @param request
	 * @param fileNamePostfix
	 * @return
	 */
	public Map<String,Object> wrapEntitys(MultipartFile[] multipartFiles, MultipartFile[] multipartFilesForVideo, HttpServletRequest request, String fileNamePostfix) {
		
		Event event=new Event();
		Event parent=new Event();
		Address discoveryAddress = new Address();
		AddressWrap discoveryAddressWrap = new AddressWrap();
		Address sourceAddress = new Address();
		Subject subject = new Subject();
		Foodbatch foodbatch = new Foodbatch();
		Food food = new Food();
		Calendar calendar = Calendar.getInstance();
		User reportor = new User();
		
		//包装地址详细信息
		discoveryAddressWrap.setRegionId(request.getParameter("region"));
		discoveryAddressWrap.setCountryId(request.getParameter("country"));
		discoveryAddressWrap.setProvinceId(request.getParameter("province"));
		discoveryAddressWrap.setCityId(request.getParameter("city"));
		discoveryAddressWrap.setAreaId(request.getParameter("area"));
		discoveryAddressWrap.setStreetId(request.getParameter("street"));
		discoveryAddressWrap.setDetailedAddress(request.getParameter("detailedAddress"));
		//不知道如何获取select中option的text内容，暂时通过数据库得到address的name，后期可以优化，直接在页面取得address的name
		discoveryAddressWrap.setRegion(cmiAddressDAO.findAddressNameById(Integer.parseInt(discoveryAddressWrap.getRegionId())));
		discoveryAddressWrap.setCountry(cmiAddressDAO.findAddressNameById(Integer.parseInt(discoveryAddressWrap.getCountryId())));
		discoveryAddressWrap.setProvince(cmiAddressDAO.findAddressNameById(Integer.parseInt(discoveryAddressWrap.getProvinceId())));
		discoveryAddressWrap.setCity(cmiAddressDAO.findAddressNameById(Integer.parseInt(discoveryAddressWrap.getCityId())));
		discoveryAddressWrap.setArea(cmiAddressDAO.findAddressNameById(Integer.parseInt(discoveryAddressWrap.getAreaId())));
		discoveryAddressWrap.setStreet(cmiAddressDAO.findAddressNameById(Integer.parseInt(discoveryAddressWrap.getStreetId())));
		/**
		 * 获取发现地址
		 */
		System.out.println(request.getAttribute("regionNAME"));
		discoveryAddress.setName(request.getParameter("detailedAddress"));
		//此处id为discoveryAddress的parent的id
		int parentId = Integer.valueOf(request.getParameter("street"));
		discoveryAddress.setId(parentId);
		discoveryAddress.setParent(addressDAO.findAddressById(parentId));
		discoveryAddress.setLevel(addressDAO.findAddressById(parentId).getLevel()+1);
		/**
		 * 父事件未知   用户需要选择subject、food、reportor  但是sourceAddress、foodbatch均为空,待在审核页面完善。
		 * 封装Event  
		 */
		if (request.getParameter("selectEvent").equals("-2")) {
			parent = eventDAO.findEventById(-2);
			//subject
			if (request.getParameter("selectSubject").equals("")) {
				subject.setName(request.getParameter("subject"));
			} else {
				subject = subjectDAO.findSubjectById(Integer.parseInt(request.getParameter("selectSubject")));
			}
			//reportor
			if (request.getParameter("selectReportor").equals("")) {
				reportor.setName(request.getParameter("reportor"));
				reportor.setUsername(request.getParameter("reportor"));
				reportor.setPassword("123456");
			} else {
				reportor = userDAO.findUserById(Integer.parseInt(request.getParameter("selectReportor")));
			}
			//food  封装Food
			if (request.getParameter("selectFood").equals("")) {
				// 新建食物  食物相关属性默认全部未知
				food.setName(request.getParameter("food"));
				food.setBrand(brandDAO.findBrandById(-2));
				food.setProducer(producerDAO.findProducerById(-2));
				food.setFoodtype(foodtypeDAO.findFoodtypeById(-2));
				foodbatch = foodbatchDAO.findFoodbatchById(-2);
				foodbatch.setFood(food);
			} else {
				food = foodDAO.findFoodById(Integer.valueOf(request.getParameter("selectFood")));
			}
		} else {
			/**
			 *  父事件已知，子事件的关联食物、地址、主体就是父事件的相关项
			 *  
			 */
			// 找到父事件相关项，与子事件关联
			parent = eventDAO.findEventById(Integer.valueOf(request.getParameter("selectEvent")));
			food = parent.getFoodbatch().getFood();
			foodbatch =  parent.getFoodbatch();
			sourceAddress = parent.getSourceAddress();
			subject = parent.getSubject();
			reportor=parent.getReportor();
			
		}
		/**
		 * 数据库插入数据时要注意的点：
		 * food要先于picture保存，因为picture引用food
		 * food用于填充picture的food字段
		 * event要先于picture保存，因为picture引用event
		 * 此处为picture赋值暂时不需要setEvent
		 */
		Set<Picture> pictureSet=new HashSet<Picture>();
		for(int i=0;i< multipartFiles.length; i++) {
			String updateFileName=multipartFiles[i].getOriginalFilename();
			String fileSuffix=updateFileName.substring(updateFileName.lastIndexOf("."));
			Picture picture=new Picture();
			picture.setFood(food);
			String pictureName = "event_"+request.getParameter("eventName")+"_"+fileNamePostfix+"_"+i+fileSuffix;
			//name与path同名
			picture.setName(pictureName);
			picture.setPath(pictureName);
			pictureSet.add(picture);
			System.out.println("pictureName==>>"+pictureName);
		}
		
		Set<Video> videoSet=new HashSet<Video>();
		for(int i=0;i< multipartFilesForVideo.length; i++) {
			String updateFileName=multipartFilesForVideo[i].getOriginalFilename();
			String fileSuffix=updateFileName.substring(updateFileName.lastIndexOf("."));
			Video video=new Video();
			video.setFood(food);
			String videoName = "event_"+request.getParameter("eventName")+"_"+fileNamePostfix+"_"+i+fileSuffix;
			//name与path同名
			video.setName(videoName);
			video.setPath(videoName);
			videoSet.add(video);
			System.out.println("videoName==>>"+videoName);
		}
		System.out.println("pictureSet==>>"+pictureSet.size());
		System.out.println("videoSet==>>"+videoSet.size());
		event.setPicturesForEvent(pictureSet);
		event.setVideosForEvent(videoSet);
		event.setFoodbatch(foodbatch);
		event.setReportor(reportor);
		event.setName(request.getParameter("eventName"));
		event.setDiscoveryAddress(discoveryAddress);
		event.setSourceAddress(sourceAddress);
		event.setSubject(subject);
		event.setDiscoveryTime(calendar);
		event.setAuditTime(calendar);
		event.setSourceTime(calendar);
		event.setCrawlTime(calendar);
		event.setDescription(request.getParameter("eventDescription"));
		event.setParent(parent);
		Map<String,Object> objects = new HashMap<>();
		objects.put("event", event);
		objects.put("food", food);
		objects.put("discoveryAddressWrap", discoveryAddressWrap);
		
		return objects;
	}


//		String testTimeHql = "select myEntity from cn.edu.scau.cmi.ema.domain.Event myEntity where  myEntity.discoveryTime <'2020-01-01 00:00:00'";

//	String testHql = "select myEntity from Event myEntity where exists (select adultertype from myEntity.adultertypesForEvent adultertype where adultertype.id ='154')";
//	String testHql2 = "select myEntity from cn.edu.scau.cmi.ema.domain.Event myEntity where myEntity.foodbatch.food.foodtype.id in (562,825,826,827,828,900,901,902,903,904,905,906,907,908,909,1198,1199,1200,1201,1202,1203,1204,1205,1206,1207,1208,1209,1210,1211,1212,1213,1214,1215,1216,1217,1218,1219,1220,1221,1222,1223,1224,1225,1226,1227,1228,1229,1230,1231,1232,1233,1234,1235,1236,1237,1238,1239,1240,1241,1242,1243,1244,1245,1246,1247,1248,1249,1250,1251,1252,1253,1254,1255,1256,1257) "; 
//重写唐锦文编写方法，原有的唐锦文编写的方法仅供参考，不要使用。
//	Set<Event> allEvents = eventDAO.findEventByCompositeProperities(hql, -1, -1);
//	System.out.println("符合条件的所有事件的数量是：" + allEvents.size());
	
	@Override
	public Set<Event> getPaginationEvents(FrontEventPagination page) {
		String hql = frontEventSqlService.createSelectHql(page, Event.class);
		hql = hql + " order by myEntity.discoveryTime desc";
		System.out.println("根据分页类得到的HQL语句是：" + hql);
		Set<Event> paginationEvents = eventDAO.findEventByCompositeProperities(hql, (page.getCurrentPagination() -1)  * page.getPaginationSize(), page.getPaginationSize());
		return paginationEvents;
	}
	
	//	唐锦文编写：用于前端不同类别的事件的获取，该方法不要了！！！！！！

	public Set<Event> getPaginationEvents2(FrontEventPagination cmiPagination) {

		// 判断是否经过跳转页框的输入
		if (cmiPagination.getInputPagination()!=0) {
			cmiPagination.setCurrentPagination(cmiPagination.getInputPagination());
		}
		Set<Event> events = null;
		// 设置搜索的初始页码
		cmiPagination.setSearchBeginCursor((cmiPagination.getCurrentPagination() - 1) * cmiPagination.getPaginationSize());
//		if (cmiPagination.getCompositeConditionMap().size() > 1) {
//			cmiPagination.setQueryBoxNumber(cmiPagination.getCompositeConditionMap().size());
//		}
			
		// 表记录的查询

		String sql = frontEventSqlService.createSelectHql(cmiPagination, Event.class);

		System.out.println("printSQL：" + sql);

//		TODO 原来的奇怪的逻辑，待测试！！！如果不是查找所有时间段，或者事件排序大于或者等于0？？？原来的>=0？？？？
		if (cmiPagination.getTimeQuantum() != 0 || cmiPagination.getIsTimeDescending()) {
			events = cmiEventDAO.findEventsByDetachedCriteria(cmiPagination);
//			TODO 2021年6月3号
			//cmiPagination.update(cmiEventDAO.countEventsByDetachedCriteriaInRange(cmiPagination));
		} else {
			events = eventDAO.findEventByCompositeProperities(sql, cmiPagination.getSearchBeginCursor(),
					cmiPagination.getPaginationSize());
//			TODO 2021年6月3号
			//cmiPagination.update(cmiEventDAO.countEventsByDetachedCriteriaInRange(cmiPagination));
		}
		// 分页类的初始化，以为不是通用的
		// 方法，这个方法countEventsByDetachedCriteriaInRange从EventDAO中转移到了CmiEventDAO类中，
		return events;
	}

	@Override
	public Integer countEvents(FrontEventPagination frontEventPagination) {
//		通用的获取记录数量的方法，但是，在前端，条件和后台的通用条件不同，需要定制
		String hql = frontEventSqlService.createCountHql(frontEventPagination, Event.class);
		return ((Long) eventDAO.createQuerySingleResult(hql).getSingleResult()).intValue();
	}
	
	// 分页类的重新设置页面属性，每次查询，page对象的一些属性都需要重置。
	public void update(FrontEventPagination frontEventPagination, int totalElements) {
		frontEventPagination.setTotalRecords(totalElements);
		// TODO 2021-05-24
//			从原来的PaginationService中复制过来，判断是否经过跳转页框的输入??????，需要好好考虑和测试
		
		if (frontEventPagination.getInputPagination()!=0) {
			frontEventPagination.setCurrentPagination(frontEventPagination.getInputPagination());
		}
		
		if (frontEventPagination.getTotalRecords() == 0) {
			frontEventPagination.setTotalPaginations(1);
		} else if (frontEventPagination.getTotalRecords() % frontEventPagination.getPaginationSize() == 0) {
			frontEventPagination.setTotalPaginations(frontEventPagination.getTotalRecords() / frontEventPagination.getPaginationSize());
		} else {
			frontEventPagination.setTotalPaginations(frontEventPagination.getTotalRecords() / frontEventPagination.getPaginationSize() + 1);
		}
		
		frontEventPagination.setInputPagination(0);
		
		if(frontEventPagination.getTotalPaginations() <=  CmiPagination.MAX_PAGE_CURSOR_SIZE + 1) {   //左边的区间和右边的区间重叠
			frontEventPagination.setSearchBeginCursor(1);
			frontEventPagination.setSearchEndCursor(frontEventPagination.getTotalPaginations());
		}else {
			if(frontEventPagination.getTotalPaginations() - frontEventPagination.getCurrentPagination()  < CmiPagination.MAX_PAGE_CURSOR_SIZE/2) {    //在右边的区间
				frontEventPagination.setSearchBeginCursor(frontEventPagination.getTotalPaginations() - CmiPagination.MAX_PAGE_CURSOR_SIZE);
				frontEventPagination.setSearchEndCursor(frontEventPagination.getTotalPaginations());
			}else if (frontEventPagination.getCurrentPagination() - 1 < CmiPagination.MAX_PAGE_CURSOR_SIZE/2) {  //在左边的区间
				frontEventPagination.setSearchBeginCursor(1);
				frontEventPagination.setSearchEndCursor(frontEventPagination.getSearchBeginCursor() + CmiPagination.MAX_PAGE_CURSOR_SIZE);
			}else {//在中间的区间
				frontEventPagination.setSearchBeginCursor(frontEventPagination.getCurrentPagination() - CmiPagination.MAX_PAGE_CURSOR_SIZE/2);
				frontEventPagination.setSearchEndCursor(frontEventPagination.getCurrentPagination() + CmiPagination.MAX_PAGE_CURSOR_SIZE/2);
			}
		}
//			前端使用的是这两个做分页控制，需要更新这两个变量。
		frontEventPagination.setTotalPaginations(frontEventPagination.getTotalPaginations());
		frontEventPagination.setCurrentPagination(frontEventPagination.getCurrentPagination());
	}

	@Override
	public FrontEventPagination updatePagination(HttpServletRequest request, FrontEventPagination frontEventPagination) {
		
//		（0）获取需要的基本食物类型等，这些项目的基本属性有EmaProjectPropertyService来完成。
		
//		Foodtypes和Adultertypes没有put到jsp页面，
//		每次都需要查找数据库，好像有一些问题，思考了其他一些选项，暂时没有想到更合理的办法。
//		使用某一个单例保存基本事件类型等一次性查询数据库的记录，然后每次从这里获取数据
		
//		选择的食物类型
		String foodtypeId = request.getParameter("foodtypeId");
		if(foodtypeId ==null) {
			frontEventPagination.setSelectFoodtype(foodtypeDAO.findFoodtypeById(-2));
		}else {
			frontEventPagination.setSelectFoodtype(foodtypeDAO.findFoodtypeById(Integer.parseInt(foodtypeId)));
		}
		
		if(mainRootFoodtypes.size() == 0) {
			getMainRootFoodtypes();
		}
		frontEventPagination.setMainRootFoodtypes(mainRootFoodtypes);
		if(mainRootAdultertypes.size() == 0) {
			getMainRootAdultertypes();
			
		}
		frontEventPagination.setMainRootAdultertypes(mainRootAdultertypes);
		
		//		(0.5) 选择的食物类型 selectFoodtypeName
		String selectFoodtypeName = request.getParameter("selectFoodtypeName");
		if(selectFoodtypeName != null) {
			Foodtype selectFoodtype = CmiSetUtil.getSoleInstance(foodtypeDAO.findFoodtypeByName(selectFoodtypeName));
			frontEventPagination.setSelectFoodtype(selectFoodtype);
		}
		//		(0.6) 选择的掺假类型，当前没能成功自动封装掺假类型，只能采用手动的方式完成，如果不是空，
		String selestAdultertypeName = request.getParameter("selectAdultertypeName");
		if(selestAdultertypeName !=null) {
			Adultertype selectAdulterype = CmiSetUtil.getSoleInstance(adultertypeDAO.findAdultertypeByName(selestAdultertypeName));
			frontEventPagination.setSelectAdultertype(selectAdulterype);
		}
		//		(0.7) 选择的时间范围
		String timeQuantumName = request.getParameter("timeQuantumName");
		if(timeQuantumName !=null) {
			switch (timeQuantumName) {
				case "近一个月":
					frontEventPagination.setTimeQuantum(1);
					break;
				case "近三个月":
					frontEventPagination.setTimeQuantum(3);
					break;
				case "近六个月":
					frontEventPagination.setTimeQuantum(6);
					break;
				case "近一年":
					frontEventPagination.setTimeQuantum(12);
					break;
				default:
					frontEventPagination.setTimeQuantum(0);
					break;
			}
		}
		
		
		//		(0.8) 选择的时间排序方式
		String timeDescendingValue = request.getParameter("timeDescendingValue");
		if(timeDescendingValue !=null) {
			switch (timeDescendingValue) {
				case "降序":
					frontEventPagination.setisTimeDescending(true);
					break;
				case "升序":
					frontEventPagination.setisTimeDescending(false);
					break;
			}
		}
		
		// （1）获取Event所有基本属性的名称：字段的名称，需要通过properties文件转换为中文名称
		Set<String> basicPropertyNames = CmiEntityUtil.getAllBasicFieldNames(Event.class);
		// （2）获取Event所有基本属性和类型的Map
		frontEventPagination.setPropertyTypeMap(CmiEntityUtil.getAllFieldNameTypeMap(Event.class));
		// （3）获取所有页面传过来的基本属性的查找条件
		Map<String, String> basicPropertyCriteriaMap = frontEventPagination.getBasicPropertyCriteriaMap();
		
		// （4）如果页面传递过来的参数是有效的输入，将有效的基本属性的输入添加到basicPropertyCriteriaMap中
		for (String basicPropertyName : basicPropertyNames) {
			String basicPropertyValue = request.getParameter(basicPropertyName);
//			TODO 后台是在PaginationService类种，中文属性名称，便于在界面显示，
			if (basicPropertyValue != null && !"".equalsIgnoreCase(basicPropertyValue.trim())) {// ??????
				basicPropertyCriteriaMap.put(basicPropertyName, basicPropertyValue);
//				basicPropertyCriteriaMap.put(properties.getProperty("event." + basicPropertyName + ".title"), basicPropertyValue);
//				basicPropertyEnglishChineseMap.put(properties.getProperty("event." + basicPropertyName + ".title"), basicPropertyValue);
			} else {
				basicPropertyCriteriaMap.put(basicPropertyName, "");
			}
		}
		
		// （5）根据分页对象中的基本查找条件和高级查找条件，查找符合分页条件的所有记录的数量
		Integer totalRecords = countEvents(frontEventPagination);
		System.out.print("----根id是" + foodtypeId + "的事件数量是：" +totalRecords);

		// （6）调用父类的updatePagination更新方法更新pagination对象的基本通用属性
        //******注意，CmiPaginationService有子类，如果采用注入的方式，会因为注入的方式不合适，不知道具体时候哪一个类，导致失败，
		//必须在@Autowired后面添加注解Qualifier.
		frontEventPagination = (FrontEventPagination) cmiPaginationService.updatePagination(frontEventPagination, totalRecords);
		return frontEventPagination;
	}

	private void getMainRootAdultertypes() {
		for(int rootAdultertypeId :mainRootAdultertypeIDs) {
			mainRootAdultertypes.add(adultertypeDAO.findAdultertypeById(rootAdultertypeId));
		}
	}

	private void getMainRootFoodtypes() {
		for(int rootFoodtypeId :mainRootFoodtypeIDs) {
			mainRootFoodtypes.add(foodtypeDAO.findFoodtypeById(rootFoodtypeId));
		}
	}
}